<template>
  <el-select
    ref="userSelect"
    v-model="selectVal"
    filterable
    remote
    clearable
    :remote-method="queryUserDataAction"
    :loading="loading"
    @change="handleChange"
  >
    <el-option
      v-for="item in userList"
      :key="item.userId"
      :label="`${item.userName}(${item.jobNumber})`"
      :value="item.userIdStr"
    >
    </el-option>
  </el-select>
</template>
<script>
import { ApiRequest } from '@api/basePage';
export default {
  name: 'UserSelect',
  prop: {
    value: {
      type: [Number, String, Array]
    }
  },
  data () {
    return {
      loading: false,
      selectVal: this.value,
      userList: [],
      getUserList: {
        url: '/usercenter/web/user/selectByName',
        type: 'post'
      }
    };
  },
  watch: {
    value (newVal) {
      this.selectVal = newVal;
    },
    /* selectVal (newVal, oldVal) {
      if (newVal !== oldVal) {
        this.$emit('input', this.selectVal);
        this.$emit('change', this.selectVal);
      }
    }, */
  },
  methods: {
    handleChange (val) {
      // 值回显父组件
      this.$emit('input', val);
      // change事件
      this.$emit('change', val);
      //
      this.$emit('onSelected', this.userList.find(item => item.userIdStr === val))
    },
    async queryUserDataAction (param) {
      this.loading = true;
      const { data, success } = await ApiRequest(
        this.getUserList.url,
        this.getUserList.type,
        { userName: param }
      );
      this.loading = false;
      if (success) {
        this.userList = data;
      }
    },
    resetSelectVal () {
      this.selectVal = ''
    }
  }
};
</script>
